package com.example.myapplication.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.myapplication.R;
import com.example.myapplication.tools.M1Utils;
import com.example.myapplication.tools.NfcAUtil;
import com.example.myapplication.tools.NfcVUtil;
import com.example.myapplication.tools.StringUtils;
import com.example.myapplication.tools.ToastUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class NfcIC extends Activity {

    Context ctx;
    EditText etIdinput,et_sector,et_block;

    NfcAdapter adapter;
    PendingIntent pendingIntent;
    IntentFilter writeTagFilters[];
    MifareClassic mfc;
    NfcAUtil util;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfc_ic);
        ctx = this;
        etIdinput = findViewById(R.id.et_id);
        et_sector = findViewById(R.id.et_sector);
        et_block = findViewById(R.id.et_block);

        adapter = NfcAdapter.getDefaultAdapter(this);
        pendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);

        writeTagFilters = new IntentFilter[] { tagDetected };


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        resolveIntent(intent);
    }

    void resolveIntent(Intent intent) {

        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
//		intent.getParcelableExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (tag != null) {
            processTag(intent);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (adapter != null)
            //设置程序不优先处理
            adapter.disableForegroundDispatch(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (adapter != null)
            //设置程序优先处理
            adapter.enableForegroundDispatch(this, pendingIntent,
                    writeTagFilters, null);
    }

    public void write(View v){
        String info = etIdinput.getText().toString();
        String temp = M1Utils.writeM1Content("GB",info);
//        List<byte[]> writeBlockList = new ArrayList<>();
        for(int i = 0 ; i < 2 ; i++){
            String strss = temp.substring(i * 32 , i*32 + 32);
            byte[] block = new byte[16];
            byte[] sInput = StringUtils.hexToByte(strss);
            if (sInput.length <= 16) {
                System.arraycopy(sInput, 0, block, 0, sInput.length);
            }
//            writeBlockList.add(block);
            writeTag(i,block);
        }

    }
    public void read(View v){
        String result = readTag();
        etIdinput.setText(result);
        Log.e("====>>>", "processTag: " + result );
    }

    AlertDialog mDialog;
    public void processTag(Intent intent) {//处理tag
        //获取到卡对象
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        String[] arr = tag.getTechList();
        if(arr.length > 0 && (arr[0].contains("android.nfc.tech.NfcA")
                    ||arr[0].contains("android.nfc.tech.NfcB"))){
            //获取卡id这里即uid
            byte[] aa = tag.getId();
            String UID = NfcVUtil.ByteArrayToHexString(aa);//
            //		String UID = flipHexStr(str);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("RFID已经连接，可以开始读写\n UID:" + UID).setTitle("提示");
            mDialog = builder.create();
            mDialog.show();

            try {
                mfc = MifareClassic.get(tag);
                if(mfc != null) {
                    mfc.connect();//建立连接
                    util = new NfcAUtil(mfc);//创建工具类，操作连接
                }
//                String info = "XH0003042";
//                String temp = M1Utils.writeM1Content(info);
//                for(int i = 0 ; i < 2 ; i++){
//                    String strss = temp.substring(i * 32 , i*32 + 32);
//                    byte[] block = new byte[16];
//                    byte[] sInput = StringUtils.hexToByte(strss);
//                    if (sInput.length <= 16) {
//                        System.arraycopy(sInput, 0, block, 0, sInput.length);
//                    }
//                    writeTag(i,block);
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            ToastUtils.showMessages("卡格式不正确",ctx);
        }


    }

    public boolean writeTag(int index,byte[] content) {
        if(!isEnable()){
            return false;
        }
        String temp = et_sector.getText().toString();
        String temp2 = et_block.getText().toString();
        int sector = Integer.parseInt(temp);
        int block = Integer.parseInt(temp2);

        try {
            if(!mfc.isConnected()){
                mfc.connect();//建立连接
            }
            boolean auth = false;
            byte[] Key = new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF};
            auth = mfc.authenticateSectorWithKeyA(sector, Key);
            if (auth) {
                // the last block of the sector is used for KeyA and KeyB cannot be overwritted
//                byte[] temp = "1313838438000000".getBytes();
//                mfc.writeBlock(3, "1313838438000000".getBytes());
                mfc.writeBlock(block + index, content);
            }
            return true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } finally {
//            try {
//                mfc.close();
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
        }
    }

    public String readTag() {
        if(!isEnable()){
            return "";
        }
        String temp = et_sector.getText().toString();
        String temp2 = et_block.getText().toString();
        int sector = Integer.parseInt(temp);
        int block = Integer.parseInt(temp2);
        boolean auth = false;
        //读取TAG
        try {
            String metaInfo = "";
            //Enable I/O operations to the tag from this TagTechnology object.
            byte[] Key = new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF};
            auth = mfc.authenticateSectorWithKeyA(sector, Key);
            if(auth){
                metaInfo = "";
                for(int i = 0; i < 2 ; i ++){
                    byte[] data = mfc.readBlock(block);
                    metaInfo += ByteArrayToHexString(data);
                }
                metaInfo = M1Utils.readM1Content(metaInfo);
            }else{
                ToastUtils.showMessages("读者卡验证错误",ctx);
            }
            return metaInfo;
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } finally {
//            if (mfc != null) {
//                try {
//                    mfc.close();
//                } catch (IOException e) {
//                    Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG)
//                            .show();
//                }
//            }
        }
        return null;

    }

    //结果大写
    public static String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F" };
        String out = "";
        for (j = 0; j < inarray.length ; j++) {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }


    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    ToastUtils.showMessages("请先连接RFID卡" ,ctx);
                    break;
                case 2:
                    ToastUtils.showMessages("接连中断，请重新连接" ,ctx);
                    break;
            }
        }
    };

    private boolean isEnable(){
        if(util == null){
            handler.sendEmptyMessage(1);
            return false;
        }
        if(mfc ==null){
            handler.sendEmptyMessage(1);
            return false;
        }
        if(!mfc.isConnected()){
            handler.sendEmptyMessage(2);
            return false;
        }
        return true;
    }

}